package com.base.servlet.http;

import com.base.servlet.constant.ContentTypeConstant;
import com.base.servlet.constant.HttpRequestHeaderKeyConstant;
import com.base.servlet.constant.HttpResponseStatus;
import lombok.Data;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Jeffrey
 * @date: 2022/01/24/9:31
 * @description:
 */
@Data
public class HttpServletResponseWrapper implements HttpServletResponse{

    /**
     * 响应头
     */
    private Map<String,String> headers;
    private HttpResponseStatus status = HttpResponseStatus.SC_OK;
    private String version = "HTTP/1.1";
    private String body = "";
    private byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
    private int contentLength = body.getBytes(StandardCharsets.UTF_8).length;
    private ServletOutputStream outputStream = new ServletOutputStream();


    public HttpServletResponseWrapper() {
        this.headers = new HashMap<>();
        /*放入默认响应头信息*/
        headers.put(HttpRequestHeaderKeyConstant.CONTENT_TYPE,
                ContentTypeConstant.get("txt"));
    }

    @Override
    public void setHeader(String name, String value) {
        headers.put(name,value);
    }


    @Override
    public void setStatus(HttpResponseStatus status) {
        this.status = status;
    }

    @Override
    public String getCharacterEncoding() {
        String contentType = this.headers.get(HttpRequestHeaderKeyConstant.CONTENT_TYPE);
        String[] split = contentType.split(";");
        String[] strings = split[1].split("=");
        return strings[1];
    }

    @Override
    public String getContentType() {
        return this.headers.get(HttpRequestHeaderKeyConstant.CONTENT_TYPE);
    }

    @Override
    public  ServletOutputStream getOutputStream() {
        return this.outputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return null;
    }

    @Override
    public void setCharacterEncoding(String charset) {

    }

    @Override
    public void setContentLength(int len) {
        headers.put(HttpRequestHeaderKeyConstant.CONTENT_LENGTH, String.valueOf(len));
    }

    @Override
    public void setContentType(String type) {
        headers.put(HttpRequestHeaderKeyConstant.CONTENT_TYPE,type);
    }

}
